﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace AdminManager.Tools
{
    /// <summary>
    /// 系统枚举类型
    /// </summary>
    public class EnumsHelper
    {

        /// <summary>
        /// 枚举 EnumModel
        /// </summary>
        public static List<EnumModel> GetEnumList<T>()
        {
            List<EnumModel> enumModels = new List<EnumModel>();
             Type enumObj = typeof(T);
            string[] keys =  Enum.GetNames(typeof(T));
            Array values = Enum.GetValues(typeof(T));
            for (int i = 0; i < keys.Length; i++)
            {
                EnumModel item = new EnumModel();
                FieldInfo fileInfo = enumObj.GetField(keys[i]); 
                item.Name = keys[i];
                item.Value = (int)values.GetValue(i);
                var display= fileInfo.CustomAttributes.Any(p => p.AttributeType == typeof(DisplayAttribute));
                if (display)
                {
                   var displayAttribute  =(DisplayAttribute)fileInfo.GetCustomAttribute(typeof(DisplayAttribute), false);
                    item.DisplayName = displayAttribute.Name;
                    item.Desc = displayAttribute.Description;
                }
                var descriptionAttribute = fileInfo.CustomAttributes.Any(p=>p.AttributeType==typeof(DescriptionAttribute));
                if (descriptionAttribute)
                {
                    item.Desc =   ((DescriptionAttribute)fileInfo.GetCustomAttribute(typeof(DescriptionAttribute), false)).Description;
                }
                enumModels.Add(item);
            }

            return enumModels;
        }

        /// <summary>
        /// 获取枚举的Display名称
        /// </summary>
        public static string DisplayName(Type t,string name)
        {
           
            //Type t = obj.GetType();
            FieldInfo fileInfo = t.GetField(name);

            var display = fileInfo.CustomAttributes.Any(p => p.AttributeType == typeof(DisplayAttribute));
            if (display)
            {
                var displayAttribute = (DisplayAttribute)fileInfo.GetCustomAttribute(typeof(DisplayAttribute), false);
                return displayAttribute.Name;
                
            }

            return "";
        }


    }
    public class EnumModel
    {
        public string Name { get; set; }
        public string  Desc { get; set; }
        public string DisplayName { get; set; }
        public int Value { get; set; }
    }
}
